import { View, Text } from '@tarojs/components'
import { useRecoilState } from 'recoil'

import flightState from '@/store/fightStore'
import Taro from '@tarojs/taro'

import './index.scss'

type Props = {
  cityList: cityListProps[]
  label: string
}

type cityListProps = {
  id: number
  cityName: string
  airportName: string
}

/**
 *
 * @param cityList '每个字母所包含的城市列表'
 * @param label '字母'
 * @returns
 */
const CityItem = ({ cityList, label }: Props): JSX.Element => {
  const [fightInfo, setfightInfo] = useRecoilState(flightState)

  const handleSetFlightInfo = ({ id, cityName, airportName }: cityListProps): void => {
    const { cityType } = fightInfo

    if (cityType === 'depart') {
      setfightInfo({
        ...fightInfo,
        departureCityId: id,
        departureCityName: cityName,
        departureAirportName: airportName
      })
    } else {
      setfightInfo({
        ...fightInfo,
        destinationCityId: id,
        destinationCityName: cityName,
        destinationAirportName: airportName
      })
    }

    Taro.navigateBack()
  }

  return (
    <View className='list-item' id={label}>
      <Text className='label'>{label}</Text>
      {cityList.map(
        ({ id, cityName, airportName }): JSX.Element => (
          <View
            key={id}
            className='name'
            onClick={() => handleSetFlightInfo({ id, cityName, airportName })}
          >
            {`${cityName} (${airportName})`}
          </View>
        )
      )}
    </View>
  )
}

export default CityItem
